from collections import deque
from utils.chrome_util import chrome
from crawler.twitter_parase import twitter
from log.logger import logger
from push.push import push
from tenacity import retry, retry_if_exception, stop_after_attempt
from exception.api_exception import ApiException

DYNAMIC_DICT = {}
LEN_OF_DEQUE = 3

@retry(stop=stop_after_attempt(3))
def query(uid):
    url = 'https://twitter.com/'+uid
    html = chrome.get_twitter(url=url)
    if html ==None:
        return
    twitters = twitter.get_user_twitter(html=html)
    name = twitters['nickname']

    articles = twitters['articles']
    logger.info('【查询动态状态】【{}】 {}条动态'.format(name,str(len(articles))))
    if len(articles)==0:
        return
    if DYNAMIC_DICT.get(uid,None) is None:
        DYNAMIC_DICT[uid] = deque(maxlen=LEN_OF_DEQUE)
        for index in range(LEN_OF_DEQUE):
            if index < len(articles):
                article = articles[index]
                if 'link' not in article:
                    continue
                DYNAMIC_DICT[uid].appendleft(article['link'])
        return

    first_twitter = articles[0]
    if first_twitter['hasTop']==True:
        if len(articles)==1:
            return
        first_twitter = articles[1]
    
    first_link = first_twitter['link']
    first_content = first_twitter['content']
    if first_link not in DYNAMIC_DICT[uid]:
        DYNAMIC_DICT[uid].appendleft(first_link)
        push.feishu_push(title='【{}】发Twitter了'.format(name),send_content=first_content,url=first_link,template="blue")
